import React, { Component } from 'react'
import { View, Text, Input } from '@tarojs/components'
import Taro from '@tarojs/taro'
import "./search.scss"
import { post } from '../../utils/http'

export default class search extends Component {

  state = {
    txt: '',
    datalist: [],
    historylist: Taro.getStorageSync('historylist') || [],
    isShowHistory: true
  }

  render() {

    let list = (
      <View className="container" >
        {
          this.state.datalist.map((item) => {
            return (
              <View className="item">
                <View className="title"
                  onClick={() => this.goDetail(item)}>
                  <Text>{item.address}</Text>
                  <Text>({item.type === 'buy' ? '求购' : '转让'})</Text>
                </View>

                <View className="desc">
                  {item.message}
                </View>
              </View>
            )
          })
        }
      </View>
    );

    let historylist = (
      <View >
        {
          this.state.historylist.map((item, index) => {
            return (
              <View key={index}
                onClick={() => this.handleClick()}>
                {item}
              </View>
            )
          })
        }
      </View >
    );

    console.log( this.state.historylist)
    return (
      <>
        <View className="searchForm">
          <Input ref="txt"></Input>
          <Text onClick={() => this.handleSearch()}>搜索</Text>
        </View>
        {
          this.state.isShowHistory ? historylist : list
        }
      </>
    )
  }


  async handleSearch() {
    let txt = this.refs.txt.value;
    let historylist = Taro.getStorageSync('historylist') || [];
    historylist.push(txt)
    Taro.setStorageSync('historylist', [...new Set(historylist)])
    let rs = await post('/index.php/trade/get_search_list', {
      keyword: txt
    })
    console.log(rs)
    this.setState({
      isShowHistory: false,
      datalist: rs.data
    })
  }

  // handleClick(e) {
  //   console.log(e)
  //   this.setState({
  //     txt: e.target.dataset.keyword
  //   })
  //   this.handleSearch();
  // }

  goDetail(item) {
    let { id, address } = item;
    Taro.navigateTo({
      url: `/pages/detail/detail?id=${id}&address=${address}`,
    })
  }
}
